package com.xuexuehai.bkm.security.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xuexuehai.bkm.domain.entity.Admin;

import java.util.Date;

/**
 * @author xuexuehai
 * @mailBox xuehai.xue@QQ.com
 * @date 2021/9/11 4:00 下午
 */
public class TokenUtil {

    private static volatile TokenUtil instance;

    private TokenUtil(){}

    public static TokenUtil getInstance(){
        if(instance == null){
            synchronized (TokenUtil.class){
                if(instance == null){
                    instance = new TokenUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 根据管理员的密码用于创建 token，其中 Audience 作为 token 的 key
     * @param admin
     * @return
     */
    public String createToken(Admin admin,Date expireDate){
        String token = JWT.create()
                .withAudience(admin.getNum())
                .withExpiresAt(expireDate)
                //.withClaim("ip","192.168.0.158")
                .withClaim("time", new Date(System.currentTimeMillis()))
                .sign(Algorithm.HMAC256(admin.getPassword()));
        return token;
    }

    /**
     * 解码获取 audience
     * @param token
     * @return
     */
    public String getAudit(String token){
        return JWT.decode(token).getAudience().get(0);
    }


}
